package com.cyw.common.config.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.github.pagehelper.Page;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PageJsonSerializer extends JsonSerializer<Page> {
    private ObjectMapper mapper;

    public PageJsonSerializer(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    public void serialize(Page page, JsonGenerator gen, SerializerProvider provider) throws IOException {
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("list", page);
        dataMap.put("total", page.getTotal());
        dataMap.put("pageNum", page.getPageNum());
        dataMap.put("pageSize", page.getPageSize());
        dataMap.put("pages", page.getPages());
        this.mapper.writeValue(gen, dataMap);
    }
}